package com.liuceng.zen.web.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.liuceng.zen.constants.Constants;
import com.liuceng.zen.pojo.domain.Image;
import com.liuceng.zen.pojo.form.ImageForm;
import com.liuceng.zen.service.ImageService;

@Controller
@RequestMapping("/common")
public class ImageController extends BaseController {
  private final Logger logger = Logger.getLogger(ImageController.class);
  @Autowired
  ImageService imageService;

  // 图片上传又盘云
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public @ResponseBody Map<String, Object> doUpload(HttpServletRequest request, ImageForm form)
      throws Exception {
    Map<String, Object> result = new HashMap<String, Object>();
    result.put("result", Constants.ERR);
    MultipartFile multipartFile = form.getFileToUpload();
    String fileName = multipartFile.getOriginalFilename();

    if (fileName != null) {
      String val[] = fileName.split("\\.");
      form.setImgFormat(val[1]);
    } else {
      form.setImgFormat(request.getParameter("imgFormat"));
    }
    byte[] fileContent = multipartFile.getBytes();

    // 验证图片尺寸大小是否符合标准
    if (form.getStatus() != null && form.getStatus() == 1) {
      BufferedImage sourceImg = ImageIO.read(new ByteArrayInputStream(fileContent));
      if (form.getImgHeight() != sourceImg.getHeight()
          || form.getImgWidth() != sourceImg.getWidth()) {
        result.put("result", Constants.FAIL);
        return result;
      }
    }

    Map<String, String> picResult = imageService.saveImage(fileContent, getCurrentUserId(), form);
    Image image = imageService.selectImageByMemberId(getCurrentUserId());
    if (Constants.OK.equals(picResult.get("result"))) {
      String picUrl = picResult.get("accessUrl");
      result.put("result", Constants.OK);
      result.put("picId", image.getId());
      result.put("picSavePath", picResult.get("picSavePath"));// 缩略图路径
      result.put("picOrignalPath", picResult.get("picOrignalPath"));// 原图路径
    }
    return result;
  }
}
